package com.example.demo.controller;

import com.example.demo.dto.UserSigninDTO;
import com.example.demo.dto.UserSignupDTO;
import com.example.demo.service.UserService;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class  AuthController {
    private final UserService userService;

    public AuthController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/home")
    public String showHome() {
        return "home";
    }

    @GetMapping("/signup")
    public String showSignup() {
        return "signup";
    }

    @GetMapping("/signin")
    public String showSignin() {
        return "signin";
    }

    @GetMapping("/success")
    public String showSuccess() {
        return "success";
    }

    @GetMapping("/fail")
    public String showFail() {
        return "fail";
    }

    @PostMapping("/signup")
    public String signupUser(UserSignupDTO userSignupDTO, Model model) {
        try {
            userService.signupUser(userSignupDTO);
            return "redirect:/success";
        } catch (IllegalArgumentException e) {
            model.addAttribute("error", e.getMessage());
            return "redirect:/signup";
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
            return "redirect:/fail";
        }
    }
    @PostMapping("/signin")
    public String signinUser(UserSigninDTO userSigninDTO,
        Model model){
        try {
            userService.signinUser(userSigninDTO);
            return "redirect:/success";
        }catch (UsernameNotFoundException e) {
            model.addAttribute("error", e.getMessage());
            return "redirect:/signup";
        } catch (BadCredentialsException e) {
            model.addAttribute("error", e.getMessage());
            return "redirect:/fail";
        }
    }

}